//
//  YSNiceProductCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/8/31.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//  好货

#import "YSNiceProductCtrl.h"
#import "YSProductListItemCell.h"
#import "YSNiceProductEditCell.h"
#import "YSHomeDataTool.h"
#import "YSMarkBottomBar.h"
#import "YSClubDataTool.h"
#import "YSProductDetailCtrl.h"
#import "UITableView+FDTemplateLayoutCell.h"

@interface YSNiceProductCtrl ()<UITableViewDataSource,UITableViewDelegate>
@property (strong, nonatomic)  UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *itemArray;
@property (assign, nonatomic) NSInteger pageIndex;
@property (assign, nonatomic) NSInteger currentMode;
@property (strong, nonatomic) YSMarkBottomBar *bottomBar;
@property (strong, nonatomic) NSMutableString *selectProdIds;//选中的id字符串，用逗号分隔

@property (strong, nonatomic) UILabel *nullPageLabel;
@property (assign, nonatomic) NSInteger deleteCount;
@end

@implementation YSNiceProductCtrl

-(NSMutableArray *)itemArray{
    if(!_itemArray){
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _currentMode = 0;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(statusChange:) name:kMarkStatusChangeNortif object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(itemStatusChange:) name:kMarkProductItemChangeNortif object:nil];
    
    [self initTableView];
    
    [self initBottomBar];
    
    self.nullPageLabel = [UIUtil getPageTipLabelWithTipText:@"您还没有收藏的商品哦"];
    [self.nullPageLabel setHidden:YES];
    [self.view addSubview:self.nullPageLabel];
    
}

-(void)initBottomBar{
    __weak YSNiceProductCtrl *ctrl = self;
     YSMarkBottomBar *bottomBar = [YSMarkBottomBar new];
     bottomBar.userInteractionEnabled = YES;
    [bottomBar  setX:0];
    [bottomBar setY:SCREENH-NavWithStatusBarH-YSMarkBottomBarHeight];
    [bottomBar setHidden:YES];
    [self.view insertSubview:bottomBar aboveSubview:self.tableView];
    
    [bottomBar setChooseOperation:^{
        NSLog(@"choose All");
         if(!self.bottomBar.statusBtn.selected){
             for (YSProductList *prod in ctrl.itemArray) {
                 [prod setStatus:NO];
             }
         }else{
             for (YSProductList *prod in ctrl.itemArray) {
                 [prod setStatus:YES];
             }
         }
        [ctrl.tableView reloadData];
    }];
    
    [bottomBar setDeleteOperation:^{
        NSLog(@"Delete");
        self.deleteCount = 0;
        ctrl.selectProdIds = [NSMutableString string];
        for (YSProductList *prod in ctrl.itemArray) {
            if(prod.status){
                 [ctrl.selectProdIds appendString:[NSString stringWithFormat:@"%ld,",prod.prodId]];
                self.deleteCount++;
            }
        }
        NSString *ids = nil;
        if(ctrl.selectProdIds.length){//去掉最后的逗号
            ids  = [NSMutableString stringWithString:[ctrl.selectProdIds substringToIndex:ctrl.selectProdIds.length-1]];
        }
        [ctrl deleteMarkWithIds:ids];
    }];
    
    self.bottomBar = bottomBar;
}


-(void)deleteMarkWithIds:(NSString *)ids{
    [YSClubDataTool markProductWithProdId:ids isMark:2 success:^(BaseResponse *result) {
        if(result.isSucc){
            if (self.deleteCount == self.itemArray.count) {
                [self.itemArray removeAllObjects];
            }
            [self requestData];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure);
    }];
}

-(void)itemStatusChange:(NSNotification *)nortif{
    for (YSProductList *prod in self.itemArray) {
        if(!prod.status){
            [self.bottomBar.statusBtn setSelected:NO];
            [self.bottomBar.deleteBtn setEnabled:NO];
            break;
        }else{
            [self.bottomBar.deleteBtn setEnabled:YES];
            [self.bottomBar.statusBtn setSelected:YES];
        }
    }
    
    for (YSProductList *prod in self.itemArray) {
        if(prod.status){
            [self.bottomBar.deleteBtn setEnabled:YES];
            break;
        }else{
            [self.bottomBar.deleteBtn setEnabled:NO];
        }
    }
    [self.tableView reloadData];
}

-(void)statusChange:(NSNotification *)nortif{
    NSNumber *status =  [nortif object];
    _currentMode = status.integerValue;
    if(status.integerValue == noEditStatusType){
        if(self.itemArray.count){
            for (YSProductList *prod in _itemArray) {
                prod.status = NO;
            }
        }
        [_tableView registerNib:[UINib nibWithNibName:@"YSProductListItemCell" bundle:nil] forCellReuseIdentifier:@"YSProductListItemCell"];
        [self.bottomBar setHidden:YES];
        [self.tableView setHeight:SCREENH-NavWithStatusBarH];
    }else{
        if(!self.itemArray.count){
            [self.bottomBar setHidden:YES];
        }else{
            [self.bottomBar setHidden:NO];
        }
        [_tableView registerNib:[UINib nibWithNibName:@"YSNiceProductEditCell" bundle:nil] forCellReuseIdentifier:@"YSNiceProductEditCell"];
        [self.tableView setHeight:SCREENH-NavWithStatusBarH-YSMarkBottomBarHeight];
    }
    [self.tableView reloadData];
}

-(void)initTableView{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH-NavWithStatusBarH)];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setBackgroundColor:PUBLIC_BG];
    [_tableView registerNib:[UINib nibWithNibName:@"YSProductListItemCell" bundle:nil] forCellReuseIdentifier:@"YSProductListItemCell"];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefereh)];
    header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.header = header;
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefereh)];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:self.tableView];
}

-(void)checkRequestData{
    if(!_itemArray.count){
        [self.tableView.header beginRefreshing];
    }else{
        [[NSNotificationCenter defaultCenter]postNotificationName:kSubPageMarkStatusChangeNortif object:[NSNumber numberWithInteger:showStatus]];
    }
}

-(void)requestData{
    if(ISLOGIN){
    [YSHomeDataTool getMarkProductListWithPageIndex:self.pageIndex success:^(YSProductListRes *result) {
        [UIUtil refreshComplete:self.tableView];
        if(result.isSucc){
            if(self.pageIndex == 0){
                [self.itemArray removeAllObjects];
            }
            [self.itemArray addObjectsFromArray:result.productList];
            [self.tableView reloadData];
            
            if(!self.itemArray.count){
                [[NSNotificationCenter defaultCenter]postNotificationName:kSubPageMarkStatusChangeNortif object:[NSNumber numberWithInteger:hideStatus]];
                [self.nullPageLabel setHidden:NO];
                [self.bottomBar setHidden:YES];
                [self.tableView setHeight:SCREENH-NavWithStatusBarH];
            }else{
                [[NSNotificationCenter defaultCenter]postNotificationName:kSubPageMarkStatusChangeNortif object:[NSNumber numberWithInteger:showStatus]];
            }
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        [UIUtil refreshComplete:self.tableView];
        ShowTips(kRequestFailure);
      }];
    }else{
        [UIUtil refreshComplete:self.tableView];
        [_nullPageLabel setHidden:NO];
    }
}

-(void)headerRefereh{
     self.pageIndex = 0;
    [self requestData];
}

-(void)footerRefereh{
     self.pageIndex ++;
    [self requestData];
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_currentMode == editStatusType){
        YSNiceProductEditCell *cell = [YSNiceProductEditCell cellWithTableView:tableView];
        [cell setProd:self.itemArray[indexPath.row]];
        return cell;
    }else{
        YSProductListItemCell *cell = [YSProductListItemCell cellWithTableView:tableView];
        [cell setProd:self.itemArray[indexPath.row]];
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(_currentMode == editStatusType){
        return [tableView fd_heightForCellWithIdentifier:@"YSNiceProductEditCell" cacheByIndexPath:indexPath configuration:^(YSNiceProductEditCell *cell) {
            [cell setProd:self.itemArray[indexPath.row]];
        }];
    }else{
        return [tableView fd_heightForCellWithIdentifier:@"YSProductListItemCell" cacheByIndexPath:indexPath configuration:^(YSProductListItemCell *cell) {
            [cell setProd:self.itemArray[indexPath.row]];
        }];
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSInteger prodId = [self.itemArray[indexPath.row] prodId];
    YSProductDetailCtrl *ctrl =  [[YSProductDetailCtrl alloc]initWithProdId:prodId];
    [self.view.superview.viewController.navigationController pushViewController:ctrl animated:YES];
    
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
